﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceModel.Syndication;
using System.Xml;

namespace CodeCamp.BL
{
	public class SyndicationBL
	{

		public List<SyndicationItem> Items { get; set; }

		public string SyndicationUrl { get; set; }

		public event EventHandler<EventArgs> Updated;

		public SyndicationBL()
		{
			Items = new List<SyndicationItem>();
		}

		public static List<SyndicationItem> Refresh(string syndicationUrl)
		{
			var webClient = new WebClient();
			var response = webClient.DownloadData(new Uri(syndicationUrl));
			return processResponse(response);

		}

		public void RefreshAsync()
		{
			var webClient = new WebClient();
			webClient.DownloadDataCompleted += (o, e) =>
			{
				Items = processResponse(e.Result);
				notify();
			};
			webClient.DownloadDataAsync(new Uri(SyndicationUrl));
		}


		private static List<SyndicationItem> processResponse(byte[] response)
		{
			XmlReader reader = XmlReader.Create(new MemoryStream(response));
			SyndicationFeed feed = SyndicationFeed.Load(reader);
			if (feed != null)
			{
				return feed.Items.OrderBy(d => d.LastUpdatedTime).ToList();
			}

			return null;
		}

		private void notify()
		{
			if (Updated != null)
			{
				Updated(this, null);
			}
		}
	}
}